package com.christina.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.christina.dto.RegisterRequest;
import com.christina.entity.User;
import com.christina.exception.BusinessException;
import com.christina.mapper.UserMapper;
import com.christina.service.UserService;
import com.christina.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户服务实现类
 * 
 * @author Christina
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> 
    implements UserService, UserDetailsService {

    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public UserServiceImpl(PasswordEncoder passwordEncoder, JwtUtil jwtUtil) {
        this.passwordEncoder = passwordEncoder;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public User register(RegisterRequest request) {
        log.info("开始注册用户: {}", request.getUsername());
        
        // 检查用户名是否已存在
        if (getByUsername(request.getUsername()) != null) {
            throw new BusinessException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (StringUtils.hasText(request.getEmail()) && getByEmail(request.getEmail()) != null) {
            throw new BusinessException("邮箱已被注册");
        }
        
        // 检查手机号是否已存在
        if (StringUtils.hasText(request.getPhone()) && getByPhone(request.getPhone()) != null) {
            throw new BusinessException("手机号已被注册");
        }
        
        // 创建用户对象
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setNickname(StringUtils.hasText(request.getNickname()) ? request.getNickname() : request.getUsername());
        
        // 保存用户
        if (!save(user)) {
            throw new BusinessException("注册失败，请稍后重试");
        }
        
        log.info("用户{}注册成功，ID: {}", request.getUsername(), user.getId());
        return user;
    }

    @Override
    public String login(String username, String password) {
        log.info("用户{}尝试登录", username);
        
        User user = getByUsername(username);
        if (user == null) {
            log.warn("登录失败，用户不存在: {}", username);
            throw new BadCredentialsException("用户名或密码错误");
        }
        
        if (!passwordEncoder.matches(password, user.getPassword())) {
            log.warn("登录失败，密码错误: {}", username);
            throw new BadCredentialsException("用户名或密码错误");
        }
        
        String token = jwtUtil.generateToken(user.getId().toString());
        log.info("用户{}登录成功", username);
        return token;
    }

    @Override
    public User getByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("is_deleted", 0);
        return getOne(queryWrapper);
    }
    
    /**
     * 根据邮箱获取用户
     */
    private User getByEmail(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        queryWrapper.eq("is_deleted", 0);
        return getOne(queryWrapper);
    }
    
    /**
     * 根据手机号获取用户
     */
    private User getByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("is_deleted", 0);
        return getOne(queryWrapper);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        return org.springframework.security.core.userdetails.User
            .withUsername(user.getUsername())
            .password(user.getPassword())
            .authorities("USER")
            .build();
    }
}